<template>
    <div style="width: 100%; height: 100%; position: relative;">
      <div style="width: 100%; height: 100%" id="chart" ref="chart"></div>
      <div class="legend-container">
        <div class="legend-content">
          <div v-for="(color, type) in orgTypeColorList" :key="type" class="legend-item">
            <div class="color-box" :style="{ backgroundColor: color }"></div>
            <span class="legend-text">{{ getTypeDescription(type) }}</span>
          </div>
          <div class="task-info">
            <span>任务类型：{{ tasktype }}</span>
            <span>状态：{{ title }}</span>
          </div>
        </div>
      </div>
    </div>
  </template>
  
  <script>
  import * as echarts from "echarts";
  
  export default {
    data() {
      return {
        userData: {},
        chartInstance: null,
        orgTypeColorList: {},
      };
    },
    props: {
      tasktype: {
        type: String,
        required: false
      },
      title: {
        type: String,
        required: false
      }
    },
    mounted() {
      // this.initData();
    },
    methods: {
      initData(data,idd) {
        this.userData = data;
        if (this.chartInstance) {
          this.chartInstance.dispose();
        }
        this.chartInstance = echarts.init(this.$refs.chart);
        this.getChartOption(idd);
        //   this.chartInstance.setOption(option);
      },
      getChartOption(idd) {
        // 处理节点和关系数据
        console.log("this.userDatahhhhhhhhhhhhhhh", this.userData);
        const { nodes, links } = this.processData(this.userData.data,idd);
        console.log("nodes, linkshhhhhhh", nodes, links);
        const option = {
          title: {},
          tooltip: {
            formatter: function (params) {
              if (params.dataType === "node") {
                return `
                      <div style="text-align:center; padding: 5px;">
                       <img src="${
                         params.data.avatar
                       }" style="width:60px;height:60px;border-radius:50%;border:2px solid #fff;box-shadow:0 0 10px rgba(0,0,0,0.1)"/><br/>
                        <b>${params.data.name}</b><br/>
                        ID: ${params.data.id}<br/>
                        ${
                          params.data.platform
                            ? "平台: " + params.data.platform
                            : ""
                        }
                      </div>
                    `;
              }
              return "";
            },
          },
          animationDurationUpdate: 1500,
          animationEasingUpdate: "quinticInOut",
          series: [
            {
              type: "graph",
              layout: "force",
              force: {
                repulsion: 500,
                edgeLength: 150,
              },
              roam: true,
              zoom: 0.3,
              focusNodeAdjacency: true,
              draggable: true,
              data: nodes,
              links: links,
              categories: [
                { name: "中心用户" },
                { name: "微博用户" },
                { name: "知乎用户" },
                { name: "二级关系" },
              ],
              edgeSymbol: ["none", "arrow"],
              edgeSymbolSize: [0, 10],
              label: {
                show: true,
                position: "right",
                formatter: "{b}",
                fontWeight: 'bold'
              },
              lineStyle: {
                color: "source",
                curveness: 0.2,
              },
              emphasis: {
                lineStyle: {
                  width: 5,
                },
              },
            },
          ],
        };
  
        this.chartInstance.setOption(option);
  
        // 响应窗口大小变化
        window.addEventListener("resize", () => this.chartInstances.resize());
      },
      processData(rootNode,idd) {
        const nodes = [];
        const links = [];
        const processedIds = new Set();
  
        // 定义不同orgType对应的颜色
        const orgTypeColors = {
          1: '#FFFFFF', // 白色 - 前后都在一个社区
          4: '#4ECDC4', // 青色 - 前在后不在一个社区
          3: '#FFD93D', // 黄色 - 后在前不在一个社区
          2: '#FF6B6B'  // 红色 - 前后都不在一个社区
        };
        this.orgTypeColorList = orgTypeColors;
        let iddd = rootNode.userId
        if(!rootNode.userId){
          iddd = idd
        }
        // 添加中心节点
        nodes.push({
          id: iddd,
          name: rootNode.userNickname || rootNode.userName,
          symbolSize: [80, 80],
          symbol: `image://${require("@/assets/images/profile1.jpg")}`,
          symbolKeepAspect: true,
          symbolClip: true,
          itemStyle: { color: "#5470c6" },
          category: 0,
          fixed: true,
          x: this.$refs.chart.offsetWidth / 2,
          y: this.$refs.chart.offsetHeight / 2,
          category: 0,
        });
        processedIds.add(iddd);
  
        // 递归处理子节点
        const processChildren = (parentNode, children, level) => {
          if (!children) return;
  
          children.forEach((child) => {
            if (!processedIds.has(child.userId)) {
              nodes.push({
                id: child.userId,
                name: child.userNickname || child.userName,
                avatar: child.avatar,
                category: level,
                // 根据orgType设置节点颜色，一阶节点大小设为3倍
                symbolSize: level === 1 ? 40 : 20,
                itemStyle: {
                  color: child.orgType ? orgTypeColors[child.orgType] : (level === 1 ? '#ffffff' : undefined)
                },
                label: level === 1 ? {
                  color: '#ffffff',
                  fontWeight: 'bold'
                } : undefined
              });
              processedIds.add(child.userId);
            }
  
            // 添加关系
            links.push({
              source: parentNode.userId,
              target: child.userId,
              // 为第一层连接添加白色样式
              lineStyle: level === 1 ? {
                color: '#ffffff',
                width: 2
              } : undefined
            });
  
            // 递归处理子节点
            if (child.children) {
              processChildren(child, child.children, level + 1);
            }
          });
        };
  
        // 从根节点开始处理
        processChildren(rootNode, rootNode.children, 1);
  
        return { nodes, links };
      },
      getTypeDescription(type) {
        const descriptions = {
          1: '前后都在一个社区',
          2: '前在后不在一个社区',
          3: '后在前不在一个社区',
          4: '前后都不在一个社区'
        };
        return descriptions[type] || '';
      },
    },
  };
  </script>
  
  <style scoped>
  .legend-container {
    position: absolute;
    top: 20px;
    left: 20px;
    background-color: rgba(0, 0, 0, 0.6);
    padding: 10px;
    border-radius: 5px;
    z-index: 1000;
    min-width: 800px;
  }
  
  .legend-content {
    display: flex;
    align-items: center;
    gap: 20px;
  }
  
  .legend-item {
    display: flex;
    align-items: center;
    white-space: nowrap;
  }
  
  .color-box {
    width: 20px;
    height: 20px;
    border-radius: 50%;
    margin-right: 10px;
    border: 1px solid rgba(255, 255, 255, 0.3);
    flex-shrink: 0;
  }
  
  .legend-text {
    color: #fff;
    font-size: 14px;
    white-space: nowrap;
  }
  
  .task-info {
    display: flex;
    gap: 20px;
    color: #fff;
    margin-left: 20px;
    white-space: nowrap;
  }
  </style>
  